//
//  M1ImagePick.m
//  NewMarryU
//
//  Created by apple on 2018/7/16.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1ImagePick.h"

@interface M1ImagePick()<UINavigationControllerDelegate, UIImagePickerControllerDelegate,TZImagePickerControllerDelegate>
@property (nonatomic ,strong) UIViewController *m1_vc;
@property (nonatomic ,assign) NSInteger m1_limit;
@property (nonatomic ,strong) PickImage m1_pick;
@end

@implementation M1ImagePick
+(instancetype)manager{
    static M1ImagePick *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[M1ImagePick alloc]init];
    });
    return manager;
}

-(void)m1_pickImages:(PickImage)block type:(PickerType)type maxCount:(NSInteger)count vc:(UIViewController *)vc{
    _m1_vc = vc;
    _m1_limit = count;
    _m1_pick = block;
    dispatch_async(dispatch_get_main_queue(), ^{
        if (type == ImagePickTypeCamera) {
            [self m1_takePhoto];
        }else{
            [self m1_localPhoto];
        }
    });
    
}
-(void)m1_localPhoto{
    TZImagePickerController *picker = [[TZImagePickerController alloc] initWithMaxImagesCount:_m1_limit delegate:self];
    picker.allowPickingVideo = NO;
    picker.allowTakePicture = NO;
    picker.allowPickingOriginalPhoto= YES;
    picker.showSelectBtn = YES;
    [_m1_vc presentViewController:picker animated:YES completion:nil];
}
-(void)m1_takePhoto{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        [M1Alert m1_alertWithTitle:nil message:@"应用相机权限受限,请在设置中启用"];
        return;
    }
    UIImagePickerController *m1_pick = [[UIImagePickerController alloc] init];
    m1_pick.delegate = self;
    m1_pick.allowsEditing = YES;
    m1_pick.sourceType = UIImagePickerControllerSourceTypeCamera;
    m1_pick.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
    [_m1_vc.navigationController.navigationBar setBackgroundImage:[UIImage m1_imageWithColor:m1_bg_color] forBarMetrics:UIBarMetricsDefault];
    [_m1_vc presentViewController:m1_pick animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    image = m1_FixImageOrientation(image);
    _m1_pick(@[image]);
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    [picker dismissViewControllerAnimated:YES completion:nil];
    _m1_pick(photos);
}
@end
